package genetic;

import java.util.ArrayList;

public class RouletteSelect implements Select {
	private ArrayList<Double> roulette;
	
	//calcula roleta, pra metodo da roleta
	@Override
	public void prepare(Population pop) {
		java.util.Collections.sort(pop.members);
		roulette = new ArrayList<Double>();
		double total = 0;
		for (Individual i:pop.members){
			total = total + i.fitness();
		}
		double runningTotal = 0;
		for (int i=0; i < pop.members.size(); i++){
			runningTotal=runningTotal+pop.members.get(i).fitness()/total;
			roulette.add(runningTotal);
		}
	}
	
	@Override
	public Individual select(Population pop) {
		double r = Math.random();
		for (int i=0; i < pop.size(); i++){
			if (roulette.get(i) <= r)
				return pop.members.get(i);
		}
		Individual ret = pop.members.get(pop.size()-1);
		return ret.clone();
	}

}
